package com.learn.core.controller.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.learn.common.annotation.Log;
import com.learn.common.annotation.UserLoginToken;
import com.learn.common.enums.BusinessType;
import com.learn.common.enums.OperatorType;
import com.learn.common.enums.ResultEnum;
import com.learn.common.utils.JwtUtil;
import com.learn.common.utils.PageResult;
import com.learn.common.utils.ResultUtil;
import com.learn.common.utils.StringUtils;
import com.learn.common.utils.result.CommonResult;
import com.learn.core.domain.*;
import com.learn.core.domain.view.GroupingUser;
import com.learn.core.dto.LGroupingDTO;
import com.learn.core.dto.LRoleDTO;
import com.learn.core.service.IGroupingUserService;
import com.learn.core.service.ILGroupingService;
import com.learn.core.service.ILGroupingUserService;
import com.learn.core.service.ILOrganizationService;
import com.learn.framework.web.controller.WebController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Description
 *
 * @author zhaohongyu
 * @ClassName LGroupingController
 * @date 2021.05.27 09:47
 */
@Api("用户群分组")
@RestController
@RequestMapping("/manager/grouping")
public class LGroupingController extends WebController<LGrouping> {

    @Autowired
    ILGroupingService ilGroupingService;
    @Autowired
    ILGroupingUserService ilGroupingUserService;
    @Autowired
    IGroupingUserService iGroupingUserService;
    @Autowired
    ILOrganizationService ilOrganizationService;

    //列表
    @ApiOperation(value = "获取列表")
    @UserLoginToken()
    @PostMapping("/list")
    public PageResult<LGrouping> list(@RequestBody LGroupingDTO lGroupingDTO){
        try {
            if (lGroupingDTO==null||lGroupingDTO.getPage()==null||lGroupingDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lGroupingDTO.getPage(),lGroupingDTO.getRows());
            QueryWrapper<LGrouping> queryWrapper = new QueryWrapper<>();
            if(StringUtils.isNotEmpty(lGroupingDTO.getName()))
                queryWrapper.like("grouping_name",lGroupingDTO.getName());
            queryWrapper.orderByDesc("create_time");
            Page<LGrouping> lGroupings = (Page<LGrouping>)ilGroupingService.list(queryWrapper);
            if (CollectionUtils.isEmpty(lGroupings)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            for (LGrouping lGrouping : lGroupings) {
                QueryWrapper<LGroupingUser> lGroupingUserQueryWrapper = new QueryWrapper<>();
                lGroupingUserQueryWrapper.eq("grouping_id",lGrouping.getGroupingId());
                int count = ilGroupingUserService.count(lGroupingUserQueryWrapper);
                lGrouping.setUserCount(count);
            }
            // 返回
            return new PageResult(lGroupings.getTotal(), lGroupings, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }

    //新增
        @ApiOperation(value = "添加")
        @PostMapping("/add")
        @UserLoginToken
        @Log(title = "添加分组", businessType = BusinessType.INSERT, operatorType = OperatorType.SYSTEM)
        public CommonResult<Object> add(@RequestBody LGrouping lGrouping, HttpServletRequest request){
            String  token = request.getHeader("token");
            String userId = JwtUtil.getUserId(token);
            try {
                if(lGrouping!=null) {
                    if (StringUtils.isEmpty(lGrouping.getGroupingName())) {
                        return (CommonResult) ResultUtil.error(ResultEnum.NOT_GROUPING_NAME);
                    }
                    lGrouping.setCreateTime(new Date());
                    lGrouping.setCreateUser(userId);
                    if (ilGroupingService.save(lGrouping)) {
                        return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
                    }
                }
            }catch (Exception e){
                return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
            }
            return  (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }

        //删除
        @ApiOperation(value = "删除")
        @PostMapping("/del")
        @UserLoginToken
        @Log(title = "删除分组", businessType = BusinessType.DELETE, operatorType = OperatorType.SYSTEM)
        public CommonResult<Object> del(@RequestBody LGrouping lGrouping){
            try {
                if(lGrouping!=null){
                    if(lGrouping.getGroupingId()!=null){
                        if(ilGroupingService.removeById(lGrouping.getGroupingId())){
                            QueryWrapper<LGroupingUser> lGroupingUserQueryWrapper = new QueryWrapper<>();
                            lGroupingUserQueryWrapper.eq("grouping_id",lGrouping.getGroupingId());
                            ilGroupingUserService.remove(lGroupingUserQueryWrapper);
                            return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
                        }
                    }
                }
            }catch (Exception e)
            {
                return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
            }
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    //更新
    @ApiOperation(value = "更新")
    @PostMapping("/edit")
    @UserLoginToken
    @Log(title = "更新分组", businessType = BusinessType.UPDATE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> edit(@RequestBody LGrouping lGrouping, HttpServletRequest request) {
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        if(lGrouping!=null){
            lGrouping.setUpdateTime(new Date());
            lGrouping.setUpdateUser(userId);
            if(ilGroupingService.updateById(lGrouping)){
                return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
            }
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    //列表
    @ApiOperation(value = "获取列表")
    @UserLoginToken()
    @PostMapping("/listGroupUser")
    public PageResult<GroupingUser> listGroupUser(@RequestBody LGroupingDTO lGroupingDTO){
        try {
            if (lGroupingDTO==null||lGroupingDTO.getPage()==null||lGroupingDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lGroupingDTO.getPage(),lGroupingDTO.getRows());
            QueryWrapper<GroupingUser> queryWrapper = new QueryWrapper<>();
            if(StringUtils.isNotEmpty(lGroupingDTO.getId()))
                queryWrapper.like("grouping_id",lGroupingDTO.getId());
            if(StringUtils.isNotEmpty(lGroupingDTO.getUserName()))
                queryWrapper.like("user_name",lGroupingDTO.getUserName());
            if(StringUtils.isNotEmpty(lGroupingDTO.getName()))
                queryWrapper.like("name",lGroupingDTO.getName());
            Page<GroupingUser> groupingUsers = (Page<GroupingUser>)iGroupingUserService.list(queryWrapper);
            if (CollectionUtils.isEmpty(groupingUsers)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            for (GroupingUser groupingUser : groupingUsers) {
                LOrganization lOrganization = ilOrganizationService.getById(groupingUser.getOrganizationId());
                if(null != lOrganization)
                    groupingUser.setOrganizationName(lOrganization.getOrganizationName());
            }
            // 返回
            return new PageResult(groupingUsers.getTotal(), groupingUsers, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }

    //新增
    @ApiOperation(value = "添加")
    @PostMapping("/addGroupUser")
    @UserLoginToken
    @Log(title = "添加分组人员", businessType = BusinessType.INSERT, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> addGroupUser(@RequestBody LGroupingUser lGroupingUser){
        try {
            if(lGroupingUser!=null) {
                if (StringUtils.isNotEmpty(lGroupingUser.getUserList())) {
                    String userList = lGroupingUser.getUserList();
                    String [] user = userList.split(",");
                    for (String str: user) {
                        LGroupingUser groupingUser = new LGroupingUser();
                        groupingUser.setGroupingId(lGroupingUser.getGroupingId());
                        groupingUser.setUserId(Integer.parseInt(str));
                        ilGroupingUserService.save(groupingUser);
                    }
                    return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
                }
            }

        }catch (Exception e){
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return  (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    //删除
    @ApiOperation(value = "删除")
    @PostMapping("/delGroupUser")
    @UserLoginToken
    @Log(title = "删除分组人员", businessType = BusinessType.DELETE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> delGroupUser(@RequestBody LGroupingUser lGroupingUser){
        try {
            if(lGroupingUser!=null){
                if(lGroupingUser.getGroupingUserId()!=null){
                    if(ilGroupingUserService.removeById(lGroupingUser.getGroupingUserId())){
                        return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
                    }
                }
            }
        }catch (Exception e)
        {
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

}
